package com.sba.core.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.sba.core.domain.Dictionary;
import com.sba.core.service.DictionaryService;

/**
 * 
 * @author feiliming
 *
 */
@Controller
@RequestMapping("${ssh.admin-path}/dict")
public class DictionaryController extends BaseController {

	private final DictionaryService dictionaryService;
	
	@Autowired
	public DictionaryController(DictionaryService dictionaryService){
		this.dictionaryService = dictionaryService;
	}
	
	@GetMapping
	public String index(Map<String, Object> model){
		return adminThemePath + "/sys/dictionary";
	}
	
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	public @ResponseBody List<Dictionary> getDictionaries(Long parentId, String type){
		List<Dictionary> dictionaries = new ArrayList<Dictionary>();
		if(parentId != null && type != null){
			dictionaries = dictionaryService.getDictionaries(parentId, type);
		}else if(type != null){
			dictionaries = dictionaryService.getDictionaries(type);
		}else{
			dictionaries = dictionaryService.getDictionaries();
		}
		return dictionaries;
	}
	
	@PostMapping("/save")
	public @ResponseBody JSONObject saveDictionary(Dictionary dictionary){
		dictionary.setCreateTime(new Date());
		dictionary.setIsDelete(0);
		JSONObject obj = new JSONObject();
		try {
			dictionaryService.saveOrUpdate(dictionary);
			obj.put("success", true);
			obj.put("msg", "保存字典成功！");
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "保存字典失败！");
		}
		return obj;
	}
	
	@GetMapping("/get")
	public @ResponseBody Dictionary getDictionary(Long id){
		return dictionaryService.findById(id);
	}
	
	@RequestMapping(path = "/delete", method = RequestMethod.POST)
	public @ResponseBody JSONObject deleteDictionary(Long id){
		List<Dictionary> pd = dictionaryService.getDictionaries(id);
		JSONObject obj = new JSONObject();
		if(pd.size() > 0){
			obj.put("success", false);
			obj.put("msg", "该字典下有子节点，禁止删除！");
			return obj;
		}else{
			Dictionary dictionary = dictionaryService.findById(id);
			dictionary.setIsDelete(1);
			try {
				dictionaryService.saveOrUpdate(dictionary);
				obj.put("success", true);
				obj.put("msg", "删除字典成功！");
			} catch (Exception e) {
				obj.put("success", false);
				obj.put("msg", "删除字典失败！");
			}
			return obj;
		}
	}
	
}
